package com.chtw.oasystem.service.impl;

import cn.hutool.core.util.IdUtil;
import com.chtw.oasystem.bean.*;
import com.chtw.oasystem.common.changelogs.ChangeLogsUtils;
import com.chtw.oasystem.mapper.ApproveLogMapper;
import com.chtw.oasystem.mapper.ApproveMapper;
import com.chtw.oasystem.mapper.RecordsMapper;
import com.chtw.oasystem.mapper.RecordsWorkMapper;
import com.chtw.oasystem.respBean.ApproveFileRespBean;
import com.chtw.oasystem.respBean.FileRespBean;
import com.chtw.oasystem.service.FileUploadService;
import com.chtw.oasystem.utils.Session;
import com.chtw.oasystem.utils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author chtw
 * @date 2020-11-14 23:15
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private RecordsMapper recordsMapper;
    @Autowired
    private RecordsWorkMapper recordsWorkMapper;

    @Autowired
    private ChangeLogServiceImpl changeLogService;

    @Autowired
    private ApproveMapper approveMapper;
    @Autowired
    private ApproveLogMapper approveLogMapper;

    @Value("${lcbs.filepath}")
    private String uploadPath;

    @Value("${lcbs.fileroot}")
    private String fileRootPath;

    @Override
    public FileRespBean saveFile(HttpSession session, MultipartFile file) throws IOException {
        // 商品图片本地保存路径
        File saveFile = new File(uploadPath);
        // 存储路径不存在则创建文件夹
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        String uuid = IdUtil.simpleUUID();
        File target = new File(uploadPath + File.separator + uuid + file.getOriginalFilename());
        file.transferTo(target);
        Records records = new Records();
        records.setPath(fileRootPath + uuid + file.getOriginalFilename());
        records.setFileName(file.getOriginalFilename());
        FullUserInfo user = Session.getCurrentUser(session);
        records.setCreateTime(TimeUtils.formatDate(new Date(), null));
        if (user != null) {
            records.setUserId(user.getUserId());
            ChangeLogs changeLog = ChangeLogsUtils.generateFileChangelog(user, file.getOriginalFilename());
            changeLogService.saveChangeLog(changeLog);
        } else {
            records.setUserId("all_user");
        }
        int insert = recordsMapper.insert(records);
        if (insert > 0) {
            FileRespBean res = new FileRespBean();
            res.setUrl_path(records.getPath());
            return res;
        }
        return null;
    }


    public FileRespBean workFileUpLoad(HttpSession session, MultipartFile file) throws IOException {
        // 商品图片本地保存路径
        File saveFile = new File(uploadPath);
        // 存储路径不存在则创建文件夹
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        String uuid = IdUtil.simpleUUID();
        File target = new File(uploadPath + File.separator + uuid + file.getOriginalFilename());
        file.transferTo(target);
        RecordsWork records = new RecordsWork();
        records.setPath(fileRootPath + uuid + file.getOriginalFilename());
        records.setFileName(file.getOriginalFilename());
        FullUserInfo user = Session.getCurrentUser(session);
        records.setCreateTime(TimeUtils.formatDate(new Date(), null));
        if (user != null) {
            records.setUserId(user.getUserId());
            ChangeLogs changeLog = ChangeLogsUtils.generateFileChangelog(user, file.getOriginalFilename());
            changeLogService.saveChangeLog(changeLog);
        } else {
            records.setUserId("all_user");
        }
        int insert = recordsWorkMapper.insert(records);
        if (insert > 0) {
            FileRespBean res = new FileRespBean();
            res.setUrl_path(records.getPath());
            return res;
        }
        return null;
    }

    @Override
    public PageInfo<Records> list(HttpSession session, int page, int size, String search) {
        try {
            PageHelper.startPage(page, size);
            RecordsExample example = new RecordsExample();
            if (search != null) {
                RecordsExample.Criteria re = example.createCriteria();
                re.andFileNameLike("%" + search + "%");
            }
            List<Records> recordsList = recordsMapper.selectByExample(example);
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser.getRoleId() > 3) {
                for (int i = recordsList.size() - 1; i >= 0; i--) {
                    Approve approve = this.getPeopleApprove(currentUser.getUserName(), recordsList.get(i).getId());
                    String path = recordsList.get(i).getPath();
                    recordsList.get(i).setPath("");
                    if (approve.getStatus() == 0) { // 1审批中 2 审批未通过 0 审批通过
                        recordsList.get(i).setPath(path);
                    }
                }
            }
            return new PageInfo<>(recordsList);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public PageInfo<RecordsWork> work_list(HttpSession session, int page, int size, String search) {
        try {
            PageHelper.startPage(page, size);
            RecordsWorkExample example = new RecordsWorkExample();
            if (search != null) {
                RecordsWorkExample.Criteria re = example.createCriteria();
                re.andFileNameLike("%" + search + "%");
            }
            List<RecordsWork> recordsList = recordsWorkMapper.selectByExample(example);
            return new PageInfo<>(recordsList);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public List<Approve> getSelfApprove(String name) {
        ApproveExample example = new ApproveExample();
        ApproveExample.Criteria re = example.createCriteria();
        re.andSubmitterEqualTo(name);
        return approveMapper.selectByExample(example);
    }

    @Override
    public Approve getPeopleApprove(String name, int recordsId) {
        ApproveExample example = new ApproveExample();
        ApproveExample.Criteria re = example.createCriteria();
        re.andSubmitterEqualTo(name);
        re.andRecordsIdEqualTo(recordsId);
        List<Approve> approves = approveMapper.selectByExample(example);
        Approve approve = new Approve();
        if (approves.size() > 0) {
            approve = approves.get(0);
            for (Approve a : approves) {
                if (TimeUtils.getTimestamp(null, a.getCreated()) > TimeUtils.getTimestamp(null, approve.getCreated())) {
                    approve = a;
                }
            }
            return approve;
        }
        approve.setStatus(-1);
        return approve;
    }

    @Override
    public boolean delete(HttpSession session, int id) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser.getRoleId() > 1) {
                throw new RuntimeException("没有权限");
            }
            Records records = recordsMapper.selectByPrimaryKey(id);
            changeLogService.saveChangeLog(ChangeLogsUtils.generateFileUploadChangeLog(currentUser.getUserName(), records.getFileName(), "删除"));
            return recordsMapper.deleteByPrimaryKey(id) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    // 获取当前用户 文件 审批详情
    @Override
    public ApproveFileRespBean approveFile(HttpSession session, int id) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            Records records = recordsMapper.selectByPrimaryKey(id);
            Approve approve = this.getPeopleApprove(currentUser.getUserName(), id);
            ApproveLogExample example = new ApproveLogExample();
            ApproveLogExample.Criteria re = example.createCriteria();
            re.andApproveIdEqualTo(approve.getId());
            List<ApproveLog> logs = approveLogMapper.selectByExample(example);
            return new ApproveFileRespBean(records.getFileName(), approve, logs);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


}
